package com.serverconnection;

import java.net.*;
import java.io.*;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;

import android.util.Log;

public class HTTPRequest {
	/**
	 * Http get request - (doesn't read cookies)
	 * 
	 * @param sUrl
	 * @return
	 * @throws IOException 
	 */
	public static HTTPData get(String sUrl) throws IOException 
	{
		HTTPData ret = new HTTPData();
		URL url = new URL(sUrl);
		String str;
		StringBuffer buff = new StringBuffer();
		
		
		BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
		while ((str = in.readLine()) != null) 
		{
			buff.append(str);
		}
		
		
		ret.content = buff.toString();
		in.close();
		return ret;
	}




	/**
	 * HTTP post request
	 * 
	 * @param sUrl
	 * @param ht
	 * @return
	 * @throws Exception
	 */
	public static HTTPData post(String sUrl, Hashtable<String, String> ht) throws Exception 
	{
		StringBuffer data = new StringBuffer();
		Enumeration<String> keys = ht.keys();
		while (keys.hasMoreElements()) {
			data.append(URLEncoder.encode(keys.nextElement(), "UTF-8"));
			data.append("=");
			data.append(URLEncoder.encode(ht.get(keys.nextElement()), "UTF-8"));
			data.append("&");
		}
		return HTTPRequest.post(sUrl, data.toString());		
	}




	/**
	 * HTTP post request
	 * 
	 * @param sUrl
	 * @param data
	 * @return
	 * @throws IOException 
	 */
	@SuppressWarnings("unchecked")
	public static HTTPData post(String sUrl, String data) throws IOException 
	{
		StringBuffer ret = new StringBuffer();
		HTTPData dat = new HTTPData();
		//String header;

		// Send data
		URL url = new URL(sUrl);
		URLConnection conn = url.openConnection();
		conn.setDoOutput(true);
		OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
		wr.write(data);
		wr.flush();

		// Get the response
		Map<String, List<String>> headers = conn.getHeaderFields();
		Set<Entry<String, List<String>>> hKeys = headers.entrySet();
		for (Iterator<Entry<String, List<String>>> i = hKeys.iterator(); i.hasNext();) {
			Entry<String, List<String>> m = i.next();

			Log.w("HEADER_KEY", m.getKey() + "");
			dat.headers.put(m.getKey(), m.getValue().toString());
			if (m.getKey().equals("set-cookie"))
				dat.cookies.put(m.getKey(), m.getValue().toString());
		}
		BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
		String line;
		while ((line = rd.readLine()) != null) {
			ret.append(line);
		}

		wr.close();
		rd.close();

		dat.content = ret.toString();
		return dat;
	}

}
